import { refreshSmsSendRecord } from '@/services/api/api-instruct-record';
import { treeReceipt } from '@/services/api/api-pressconference';
import { CheckSquareOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { Col, message, Row, Space, Tag, Tooltip } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import { useState } from 'react';
import ListReceipt from './ListReceipt';

interface ReceiptAssignProps {
  id: string;
  deadlineTime: string;
  receipt: string;
  type: 'read' | 'receipt';
  isRun: boolean;
}

const ReceiptAssign: React.FC<ReceiptAssignProps> = ({
  id,
  receipt,
  deadlineTime,
  type,
  isRun,
}) => {
  const [dataTree, setDataTreeState] = useState<DataNode[]>();
  const [dataCheckTree, setDataCheckTreeState] = useState<any>();

  const checkTreeKeys = new Array();

  const [createdCombineId, setCreatedCombineIdState] = useState<string>();

  /**
   * 加载组织树请求网络
   */
  const loadData = async () => {
    try {
      const response = await treeReceipt({ recordId: id, type: type === 'read' ? 1 : 2 });

      if (response.code === 0) {
        setDataTreeState(readyTreeData(response.data));
        setDataCheckTreeState(checkTreeKeys);
      }
    } catch (error) {}
  };

  const loadRefreshSmsSendRecord = async () => {
    const response = await refreshSmsSendRecord({ instructId: id });

    if (response.code === 0) {
      message.success('更新成功');
      setTimeout(() => {
        loadData();
      }, 500);
    }
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: Array<UserData.Organization>): any {
    const treeData = new Array();

    if (data) {
      data.forEach((val, idx, array) => {
        console.log('=====', val.name, val.smsSendStatus, val.smsPhone, val.smsReason);
        treeData.push({
          title: (
            <Space>
              {val.isOrganization == 0 && val.isAddress == 0 ? (
                <>
                  <Tooltip title={`电话：${val.accountPhone}`}>{val.name}</Tooltip>

                  {val.isView !== undefined && val.isView === 1 ? (
                    <Tag>已阅读</Tag>
                  ) : (
                    <Tag>未阅读</Tag>
                  )}
                  {val.isReply !== undefined && val.isReply === 1 ? (
                    <Tag>已回复</Tag>
                  ) : (
                    <Tag>未回复</Tag>
                  )}
                </>
              ) : (
                val?.name
              )}
            </Space>
          ),
          key: val.id,
          icon:
            val.isView !== undefined && val.isView === 1 ? (
              <CheckSquareOutlined />
            ) : (
              <QuestionCircleOutlined />
            ),
          children: readyTreeData(val.children as Array<UserData.Organization>),
        });

        if (val.isView !== undefined && val.isView === 1 && !val.children) {
          checkTreeKeys.push(val.id);
        }
      });
    }
    return treeData;
  }

  return (
    <DrawerForm
      title={'回执情况'}
      trigger={<a>{receipt}</a>}
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: '1000px',
      }}
      submitter={false}
      onOpenChange={(visible) => {
        if (visible) {
          loadData();
        }
      }}
    >
      {dataTree && dataTree.length ? (
        <Row>
          <Col span={10}>
            <Tree
              treeData={dataTree}
              checkedKeys={dataCheckTree}
              checkable
              style={{ width: '100%' }}
              defaultExpandAll={true}
              onSelect={(selectedKeys, info) => {
                console.log('==1==', info);

                if (info.selected && info.node.checked) {
                  console.log('====', selectedKeys, info);
                  setCreatedCombineIdState(info.node.key as string);
                }
              }}
            />
          </Col>
          <Col span={14}>
            <ListReceipt
              recordId={id}
              deadlineTime={deadlineTime}
              createdCombineId={createdCombineId}
              type={type === 'read' ? 1 : 2}
            />
          </Col>
        </Row>
      ) : (
        '暂无数据'
      )}
    </DrawerForm>
  );
};

export default ReceiptAssign;
